package de.hbrs.ooka.crs.servlet;

import de.hbrs.ooka.beans.ConferenceBeanStatelessLocal;
import de.hbrs.ooka.beans.UserBeanStatelessLocal;
import de.hbrs.ooka.beans.UserSessionStatefulLocal;
import de.hbrs.ooka.crs.servlet.constants.WebPageNames;
import de.hbrs.ooka.enums.Role;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterAtConfServlet extends AbstractViewServlet {

    @EJB
    private ConferenceBeanStatelessLocal confBean;
    @EJB
    private UserBeanStatelessLocal userBean;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        UserSessionStatefulLocal crsBean = this.getCrsBean(request);
        String redirection = "";
        RequestDispatcher rd = null;

        if (crsBean == null || !this.isUserAuthenticated(crsBean.getUser(), Role.PARTICIPANT)) {
            request.setAttribute("message", "Not logged in");
            request.setAttribute("redirect", WebPageNames.LoginViewPage);
            rd = request.getRequestDispatcher("/" + WebPageNames.ErrorPage + ".jsp");
            if (rd != null) {
                rd.forward(request, response);
            }
        } else {
            String action = request.getParameter("action");
            if (action == null) {
                request.setAttribute("conference", request.getParameter("conference"));
                rd = request.getRequestDispatcher("/" + WebPageNames.RegisterAtConf + ".jsp");
                if (rd != null) {
                    rd.forward(request, response);
                }
            } else if (action.equalsIgnoreCase("register")) {
                String confname = request.getParameter("conf");
                
                this.userBean.registerAtConf(crsBean.getUser(), this.confBean.getConference(confname));
                
                request.setAttribute("message", "Successfully registered at conference");
                request.setAttribute("redirect", WebPageNames.ParticipantViewPage);
                rd = request.getRequestDispatcher("/" + WebPageNames.ActionSuccessfulPage);
                if (rd != null) {
                    rd.forward(request, response);
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
